<template>
    <div class="container">
        <!-- <div class="flex">
            <el-form
                class="guide_coefficient"
                :inline="true"
                :model="coefficient"
            >
                <el-form-item label="批量修改价格" prop="goods_price">
                    <el-input-number
                        :step="0.1"
                        :min="1"
                        :precision="2"
                        v-model="coefficient.goods_price"
                    ></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="setGuideCoefficient"
                        >匹配修改价格</el-button
                    >
                </el-form-item>
            </el-form>
            <el-form :inline="true" :model="coefficient">
                <el-form-item label="标价倍数" prop="purchase_coefficient">
                    <el-input-number
                        :step="0.1"
                        :min="1"
                        :precision="2"
                        v-model="coefficient.purchase_coefficient"
                    ></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="setPurchaseCoefficient"
                        >批量设置标价倍数</el-button
                    >
                </el-form-item>
            </el-form>
        </div> -->
        <egrid
            border="border"
            v-bind="$attrs"
            v-on="$listeners"
            :data="data"
            :columns="columns"
            :columns-props="columnsProps"
        ></egrid>
    </div>
</template>

<script>
/* eslint-disable */
import Vue from "vue";
import { flatten } from "@/utils/sku";
import { diffArary } from "@/utils";
import Egrid from "egrid";
import ElUploadImage from "@/components/el-upload-image.vue";
Vue.use(Egrid);
export default {
    props: {
        skusData: {
            type: Array,
            default() {
                return [];
            }
        },
		datalist:{
			type: Array,
			default:[]
		}
    },
    components: {
        ElUploadImage
    },
    computed: {
        skusList() {
            return flatten(this.skusData).map(item => ({
                skus: item.skus,
                ids: item.skus.reduce(
                    (total, prev, index) =>
                        `${total}${prev.k_id}-${prev.v_id}${
                            index === item.skus.length - 1 ? "" : "_"
                        }`,
                    ""
                )
            }));
        },
        columns() {
            const specList = this.skusData.map(item => ({
                width: "auto",
                label: item.value,
                formater(row) {
                    const sku = row.skus.find(sku => sku.k === item.value);
                    return sku.v;
                }
            }));
            return [
                ...specList,
				{
				    label: "图片",
				    width: 200,
				    component: Vue.extend({
				        props: ["row"],
				        render() {
							
				            return (
				                <ElUploadImage
								v-model={this.row.image}
				                    onChange={e => (this.row.image = e)}
				                ></ElUploadImage>
				            );
				        }
				    })
				},
				// <el-upload-image v-model="formData.img" :limit="1" :title="title"></el-upload-image>
       //          {
       //              label: "图片",
       //              width: 200,
       //              component: Vue.extend({
       //                  props: ["row"],
       //                  render() {
							// console.log(this.row.image,'this.row.image')
							// this.row.image_id= [{
							// 	name: this.row.image.full_url,
							// 	url: this.row.image.full_url
							// }]
       //                      return (
       //                          <ElUploadImage
							// 		value={this.row.image_id}
       //                              onChange={e => (this.row.image_id = e)}
       //                          ></ElUploadImage>
       //                      );
       //                  }
       //              })
       //          },
                {
                    label: "库存",
                    width: 150,
                    component: Vue.extend({
                        props: ["row"],
                        render() {
                            return (
                                <ElInputNumber
                                    style="width:100%"
                                    placeholder="请输入"
                                    value={this.row.stock_num}
                                    step={1}
                                    min={0}
                                    controls={false}
                                    precision={0}
                                    oninput={e => (this.row.stock_num = e)}
                                ></ElInputNumber>
                            );
                        }
                    })
                },
                {
                    label: "售价",
                    width: 160,
                    component: Vue.extend({
                        props: ["row"],
                        render() {
                            return (
                                <ElInputNumber
                                    style="width:100%"
                                    placeholder="请输入"
                                    value={this.row.goods_price}
                                    step={1}
                                    min={0}
                                    controls={false}
                                    precision={2}
                                    oninput={e => (this.row.goods_price = e)}
                                ></ElInputNumber>
                            );
                        }
                    })
                },
       //          {
       //              label: "进货价",
       //              width: 160,
       //              component: Vue.extend({
       //                  props: ["row"],
       //                  render() {
							// console.log(this,'this ssss')
       //                      return (
       //                          <ElInputNumber
       //                              style="width:100%"
       //                              placeholder="请输入"
       //                              value={this.row.line_price}
       //                              step={1}
       //                              min={0}
       //                              controls={false}
       //                              precision={2}
       //                              oninput={e => (this.row.line_price = e)}
       //                          ></ElInputNumber>
       //                      );
       //                  }
       //              })
       //          },
				{
				    label: "划线价",
				    width: 160,
				    component: Vue.extend({
				        props: ["row"],
				        render() {
				            return (
				                <ElInputNumber
				                    style="width:100%"
				                    placeholder="请输入"
				                    value={this.row.agent_price}
				                    step={1}
				                    min={0}
				                    controls={false}
				                    precision={2}
				                    oninput={e => (this.row.agent_price = e)}
				                ></ElInputNumber>
				            );
				        }
				    })
				},
                {
                    label: "编码",
                    width: 150,
                    component: Vue.extend({
                        props: ["row"],
                        render() {
							// this.row.goods_sku_no = 0
                            return (
							<ElInput
								style="width:100%"
								placeholder="请输入"
								value={this.row.goods_sku_no}
								oninput={e =>
									(this.row.goods_sku_no = e.trim())
								}
							></ElInput>
                            );
                        }
                    })
                },
                {
                    label: "重量",
                    width: 150,
                    component: Vue.extend({
                        props: ["row"],
                        render() {
                            return (
							<ElInput
								style="width:100%"
								placeholder="请输入"
								value={this.row.goods_weight}
								oninput={e =>
									(this.row.goods_weight = e.trim())
								}
							></ElInput>
                            );
                        }
                    })
                }
            ];
        }
    },
    watch: {
		datalist:{
			deep:true,
			immediate:true,
			handler(){
				this.data = this.datalist
				console.log(this.datalist,'this.datalist')
			}
		},
        skusList: {
            deep: true,
            immediate: true,
            handler(newSkus, oldSkus) {
				console.log(newSkus,oldSkus,'oldSkus')
                if (!newSkus.length) return (this.data = []);
                if(!this.$route.query.id){if (!oldSkus || !oldSkus.length) return this.initData(newSkus);}
				
                if (newSkus.length === oldSkus.length) {
                    // 当规格名和规格值数量未发生变化，更新 skus 即可
                    if(this.$route.query.id){
						console.log(newSkus,'newSkys')
						return (this.data = newSkus.map((item, index) => ({
						    ...this.data[index],
						    ...item
						})));
					}else{
						return (this.data = newSkus.map((item, index) => ({
						    ...this.data[index],
						    ...item
						})));
					}
                }
				console.log('123')
                // 当规格名的数量发生了变化
                if (newSkus[0].skus.length !== oldSkus[0].skus.length)
                    return this.initData(newSkus);
                const diffIds = this.diffIds(newSkus, oldSkus);
                if (newSkus.length > oldSkus.length) {
                    // 当添加了规格值
                    let data = [];
					console.log('1123',newSkus,this.data,'data')
                    newSkus.forEach(item => {
                        const sku = this.data.find(
                            _item => _item.ids === item.ids
                        );
						console.log(this.data,sku,'sku')
                        if (sku) {
                            data.push(sku);
                        } else {
                            data.push({
                                ...item,
                                stock_num: "",
                                goods_price: "",
                                goods_sku_no: "0",
                                goods_weight: "0",
                                line_price: "",
								agent_price:"",
                            });
                        }
                    });
                    this.data = data;
                } else {
                    // 当删除了规格值
                    this.data = this.data.filter(
                        _item => !diffIds.includes(_item.ids)
                    );
                }
            }
        }
    },
    data: () => ({
        data: [],
        // [
        //   {
        //     ids: '1-11_2-21',
        //     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":21,"v":"大"}],
        //     price: '',
        //     guide: '',
        //   },
        //   {
        //     ids: '1-11_2-22',
        //     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":22,"v":"小"}],
        //     price: '',
        //     guide: '',
        //   }
        // ]
        coefficient: {
            goods_price: 0,
            guide_coefficient: 1.2
        },
        columnsProps: {
            align: "center",
            minWidth: 100
        }
    }),
    methods: {
        getData() {
            return this.data;
        },
        diffIds(skusList1, skusList2) {
            // 两个数据的 ids 进行相差
            skusList1 = skusList1.map(item => item.ids);
            skusList2 = skusList2.map(item => item.ids);
            return diffArary(skusList1, skusList2);
        },
        initData(skusList) {
			console.log(skusList,'skusList')
			this.data = skusList.map(item => ({
			    ...item,
			    // 初始化属性
			    stock_num: "",
			    goods_price: "",
			    goods_sku_no: "",
			    goods_weight: "",
			    line_price: "",
				agent_price:"",
			}));
            
			console.log(skusList,this.data,'this.data')
        },
        setGuideCoefficient() {
            const goods_price = this.coefficient.goods_price;
            this.data = this.data.map(item => ({
                ...item,
                goods_price: goods_price
            }));
        },
        setPurchaseCoefficient() {
            const purchase_coefficient = this.coefficient.purchase_coefficient;
            this.data = this.data.map(item => ({
                ...item,
                goods_weight: (item.goods_sku_no || 0) * purchase_coefficient
            }));
        }
    }
};
</script>

<style scoped>
.flex {
    display: flex;
}
.flex .guide_coefficient {
    margin-right: 20px;
}
</style>